<template>
  <div class="relative page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" align="center" @loadData="loadData">
      <template #staffName="{ record }">
        <div>{{ record.staffName }}</div>
        <div class="gray">{{ record.staffPostName }}</div>
        <tag :type="getStatusNameColor(record)">{{ record.statusName }}</tag>
      </template>

      <template #siteInfoList="{ record }">
        <template v-if="record.siteInfoList && record.siteInfoList.length > 0">
          <more-popup maxWidth="250px" :list="record.siteInfoList" />
        </template>
      </template>

      <template #titleSlot="{ column }">
        <div :class="column.week == '今天' ? 'blue' : ''">
          <div>{{ column.title }} | {{ column.week }}</div>
        </div>
      </template>

      <template v-for="day in days" #[day.title]="{ record }" :key="day">
        <div class="relative flex items-center justify-center custom">
          <span :class="getLabelColor(record, day.title)">{{ record[day.title]?.label }}</span>
          <template v-if="record[day.title]?.value > 0">
            <a-popover
              trigger="click"
              popup-container="#app"
              position="tr"
              :content-style="{
                width: '450px',
                background: '#ffffff',
                boxShadow: '0px 4px 10px 0px rgba(0, 0, 0, 0.15)',
                borderRadius: '8px 8px 8px 8px',
                border: '1px solid #e8e8e8',
              }"
              @click="() => onClickPopover(record[day.title])"
              @popup-visible-change="handlePopupChange"
              v-model:popup-visible="record[day.title].popupVisible"
            >
              <template #title>
                <div class="popover-title">
                  <div>{{ record[day.title].label }}{{ titleIndex }}</div>
                </div>
              </template>
              <span class="ml-1.5 cursor-pointer number">
                {{ record[day.title]?.value }}
              </span>
              <template #content>
                <!-- 司机排班弹窗 -->
                <message-popover :record="record" :titleIndex="titleIndex" :day="day.title" @indexChange="handleIndexChange" />
              </template>
            </a-popover>
          </template>
          <template v-else>
            <span
              class="ml-1.5 cursor-pointer number"
              :class="{ 'gray-bg': record[day.title]?.value == 0, 'cursor-not-allowed': record[day.title]?.value == 0 }"
            >
              {{ record[day.title]?.value }}
            </span>
          </template>
        </div>
      </template>
    </table-index>
  </div>
</template>

<script setup lang="ts" name="diverSchedule">
  import MessagePopover from './popover/message-popover.vue'
  import { useFetchTableDataApi, useTable } from '@/hooks/table'
  import { ref, reactive, computed } from 'vue'
  import dayjs from 'dayjs'
  import { onMounted } from 'vue'
  import { setTableRowSpan } from '@/utils/table-row-span'
  import { getDriverSchedule } from '@/api/driver'
  import { useSysDict, sysDict, usePageDict } from '@/hooks/useDict'

  const staffDict = usePageDict('staffDict')
  useSysDict(['staff_post'])

  const queryParam = reactive<any>({
    time: [],
    scrollTop: 0,
  })

  const searchList = computed(() => {
    return [
      {
        label: '员工姓名',
        prop: 'idList',
        type: 'remote-select',
        attrs: {
          type: 'driver_schedule_staff',
          multiple: true,
        },
      },
      {
        label: '归属门店',
        prop: 'orgAuthIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
          multiple: true,
        },
      },
      { label: '员工状态', prop: 'staffStatusList', type: 'a-select', multiple: true, options: staffDict.staffStatusList },
      { label: '员工岗位', prop: 'staffPostList', type: 'a-select', multiple: true, options: sysDict.staff_post },
      {
        label: '时间',
        prop: 'time',
        type: 'i-range-picker',
        disabledDate: (current: string) => {
          const today = dayjs().startOf('day')
          const cur = dayjs(current)
          return cur.isBefore(today.add(-1, 'month')) || cur.isAfter(today.add(3, 'month'))
        },
        change: (value = []) => {
          queryParam.startTime = value[0]
          queryParam.endTime = value[1]
        },
      },
    ]
  })

  const table = useTable({
    columns: [
      { title: '员工姓名', dataIndex: 'staffName', slotName: 'staffName', align: 'center', fixed: 'left', width: 150 },
      { title: '归属门店', dataIndex: 'siteInfoList', slotName: 'siteInfoList', align: 'center', fixed: 'left', width: 150 },
      { title: '数据汇总', dataIndex: 'ordersTotal', align: 'center', fixed: 'left' },
    ],
    spanMethod: (data: { record: any; column: any; rowIndex: number; columnIndex: number }) => {
      const { record, column } = data
      if (record.mergeCell?.includes(column.dataIndex)) {
        const rowspan = record[`rowspan_${column.dataIndex}`]
        if (rowspan) {
          return { rowspan: rowspan, colspan: 1 }
        } else {
          return { rowspan: 0, colspan: 0 }
        }
      }
    },
  })

  const getStatusNameColor = (record: any) => {
    switch (record.status) {
      case 1:
        return 'primary'
      case 2:
      case 3:
        return 'default'
    }
  }

  const dataSummaryKey = ['giveCarOrderNum', 'returnCarOrderNum', 'changeCarOrderNum']
  const dataSummaryTitle = ['交车单', '还车单', '换车单']
  const days = ref<any[]>([])

  const loadData = (page?: any) => {
    const result: any[] = []
    days.value = []
    table.columns = table.columns.slice(0, 3)

    // 需要合并的字段名，按照合并登记来排序
    const colFields = ['staffName', 'siteInfoList']

    const fn = useFetchTableDataApi(table, queryParam, getDriverSchedule)
    fn(page).then((res: any) => {
      res.data[0].everydayData?.forEach((item: any) => {
        days.value.push({
          title: item.dateStr,
          week: item.week,
          titleSlotName: 'titleSlot',
          dataIndex: item.dateStr,
          slotName: item.dateStr,
          align: 'center',
          width: 135,
        })
      })

      /**
       * 将每日数据拆分成三个对象(交车单、还车单、换车单)，每个对象包含每日数据和对应的工单类型
       * 具体格式为：
       * [
       *  { 4月24日: { label: '交车单', value: 1, changeCarOrderId: 1, giveCarOrderId: 1, returnCarOrderId: 1, popupVisible: false } },
       *  { 4月24日: { label: '还车单', value: 1, changeCarOrderId: 1, giveCarOrderId: 1, returnCarOrderId: 1, popupVisible: false } },
       *  { 4月24日: { label: '换车单', value: 1, changeCarOrderId: 1, giveCarOrderId: 1, returnCarOrderId: 1, popupVisible: false } },
       * ]
       */
      for (let i = 0; i < res.data.length; i++) {
        for (let z = 0; z < 3; z++) {
          const everydayItem: any = {}
          for (let j = 0; j < res.data[i].everydayData.length; j++) {
            everydayItem[[res.data[i].everydayData[j].dateStr]] = {
              label: dataSummaryTitle[z],
              value: res.data[i].everydayData[j][dataSummaryKey[z]],
              changeCarOrderId: res.data[i].everydayData[j].changeCarOrderId,
              giveCarOrderId: res.data[i].everydayData[j].giveCarOrderId,
              returnCarOrderId: res.data[i].everydayData[j].returnCarOrderId,
              popupVisible: false,
            }
          }
          result.push({
            ...res.data[i],
            // 工单总数
            ordersTotal: `${dataSummaryTitle[z]} - ${res.data[i][dataSummaryKey[z]]}`,
            ...everydayItem,
          })
        }
      }
      /** 遍历需要合并单元格 */
      setTableRowSpan(result, colFields)

      table.columns = [...table.columns, ...days.value]
      table.dataList = result
    })
  }

  const getLabelColor = (record: any, day: string) => {
    switch (record[day]?.label) {
      case '交车单':
        return 'cst-orange'
      case '还车单':
        return 'cst-green'
      case '换车单':
        return 'cst-purple'
    }
  }

  const titleIndex = ref(1)
  const handleIndexChange = (index: number) => {
    titleIndex.value = index
  }

  const curPopover = ref<any>()
  const onClickPopover = (record: any) => {
    curPopover.value = record
  }

  const handlePopupChange = (visible: boolean) => {
    if (!visible) {
      titleIndex.value = 1
    }
  }

  onMounted(() => {
    const element = document.querySelector('.arco-scrollbar-container .arco-table-body')
    if (element) {
      element.addEventListener('scroll', () => {
        if (curPopover.value) {
          curPopover.value.popupVisible = false
        }
      })
    }

    loadData()
    console.log('days', days.value)
  })
</script>

<style scoped lang="less">
  .page-container {
    position: relative;
  }

  .popover-content {
    width: 400px;
    background: #ffffff;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.15);
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #e8e8e8;
  }

  .number,
  .gray-bg {
    min-width: 25px;
    min-height: 16px;
    padding: 0px 10px;
    background-color: #1890ff;
    color: #fff;
    border-radius: 10px 10px 10px 10px;
  }
  .blue {
    color: #3370ff;
  }
  .gray {
    color: #86909c;
  }
  .gray-bg {
    background-color: #f2f3f5;
    color: #c7c7c7;
  }

  .cst {
    &-orange {
      color: rgba(255, 125, 0, 1);
    }

    &-green {
      color: rgba(0, 180, 42, 1);
    }

    &-purple {
      color: rgba(114, 46, 209, 1);
    }
  }
</style>
